package org.lql.chaos.mq.rabbitmq.producer;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.lql.chaos.mq.rabbitmq.constant.RabbitMQConstant;
import org.lql.chaos.mq.rabbitmq.pojo.OrderInfo;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author: liangqinglong
 * @date: 2025-08-09 00:20
 * @description:
 **/
@Slf4j
@Service
public class OrderMessageProducer {

	@Autowired
	@Qualifier("rabbitTemplate")
	private RabbitTemplate rabbitTemplate;

	public void sendOrderMessage(OrderInfo orderMessage) {
		CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
		String context = JSONObject.toJSONString(orderMessage);
		rabbitTemplate.convertAndSend(
				RabbitMQConstant.ORDER_EXCHANGE,
				RabbitMQConstant.ORDER_ROUTING_KEY,
				context,
				message -> {
					// 设置单条消息的过期时间
					message.getMessageProperties().setMessageId(orderMessage.getOrderId() + ":" + cd.getId());
					// 设置消息持久化
					message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
					return message;
				},
				cd);
		log.info("发送 Order 消息: {}", orderMessage);
	}

	public void sendOrderMessageWithExpiration(OrderInfo orderMessage, long delayMillis) {
		CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend(
				RabbitMQConstant.ORDER_EXCHANGE,
				RabbitMQConstant.ORDER_ROUTING_KEY,
				orderMessage,
				message -> {
					// 设置单条消息的过期时间
					message.getMessageProperties().setMessageId(orderMessage.getOrderId());
					// 设置消息持久化
					message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
					// 设置消息的过期时间
					message.getMessageProperties().setExpiration(String.valueOf(delayMillis));
					return message;
				},
				cd);
		log.info("发送 Order 动态设置延迟时间 {} 消息: {}", delayMillis, orderMessage);
	}
}
